package ast.nodes;

import scanner.Token;
import ast.ASTNode;
import ast.Evaluation;

/**
 * The first child of a While node is a RegExNode, the subsequent children are Series Nodes
 * which are run as long as the RegExNode holds true.
 *
 */
public class WhileNode extends CommandNode {

    public WhileNode()
    {
        super();
    }
    
    public WhileNode(Token data)
    {
        super(data);
    }

    @Override
    public String toString(int depth) {

        String seriesStr = "";
        for (ASTNode child : getChildren()) {
            seriesStr += child.toString(depth+1);
        }

        return indent(depth) + this.data.getTokenString() + ":" + seriesStr;
    }

    /**
     * Use the first child as the RegExNode and loop over the subsequent children until the regEx
     * fails.
     */
    @Override
    public void run(Evaluation input) throws Exception {
        RegExNode ren = null;
        for(ASTNode child : children)
        	if(child instanceof RegExNode)
        		ren = (RegExNode) child;
        if(ren != null)
        	while(ren.match(input.getCurrentLine()))
        		for(ASTNode child : children)
        			if(child instanceof SeriesNode)
        				child.run(input);
    }
}
